package org.ciallo.simplemusicplayer.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputLayout;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongAdapter;
import org.ciallo.simplemusicplayer.data.model.Playlist;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.SongOptionsDialogFragment;
import org.ciallo.simplemusicplayer.viewmodel.PlaylistViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jukomu
 * @Description: 显示特定歌单内歌曲列表的 Activity
 * @Package: org.ciallo.simplemusicplayer.activity
 * @Project: SimpleMusicPlayer
 * @name: PlaylistSongsActivity
 * @Date: 2025/5/30-03:08
 * @Filename: PlaylistSongsActivity
 */
public class PlaylistSongsActivity extends AppCompatActivity {
    public static final String EXTRA_PLAYLIST_ID = "extra_playlist_id";
    public static final String EXTRA_PLAYLIST_NAME = "extra_playlist_name";
    public static final String EXTRA_PLAYLIST_COVER_URI = "extra_playlist_cover_uri";

    private long playlistId;
    private String playlistNameFromIntent;
    private Playlist currentPlaylistForMenu; // 用于菜单操作，如删除

    private Toolbar toolbar;
    private RecyclerView recyclerViewSongs;
    private SongAdapter songAdapter;
    private TextView tvEmptyPlaylist;
    private FloatingActionButton fabPlayAll;

    private PlaylistViewModel playlistViewModel;
    private SharedViewModel sharedViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist_songs);

        Intent intent = getIntent();
        playlistId = intent.getLongExtra(EXTRA_PLAYLIST_ID, -1L);
        playlistNameFromIntent = intent.getStringExtra(EXTRA_PLAYLIST_NAME);

        if (playlistId == -1L) {
            Toast.makeText(this, "无效的歌单ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        toolbar = findViewById(R.id.toolbar_playlist_songs_activity);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle(playlistNameFromIntent != null ? playlistNameFromIntent : "歌单歌曲");
        }

        recyclerViewSongs = findViewById(R.id.recyclerView_playlist_songs_activity);
        tvEmptyPlaylist = findViewById(R.id.textView_empty_playlist_songs_activity);
        fabPlayAll = findViewById(R.id.fab_playlist_songs_play_all);

        playlistViewModel = new ViewModelProvider(this).get(PlaylistViewModel.class);
        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);

        setupRecyclerView();
        observeViewModel();

        fabPlayAll.setOnClickListener(v -> {
            List<Song> currentList = songAdapter.getCurrentList();
            if (currentList != null && !currentList.isEmpty() && sharedViewModel != null) {
                sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), 0);
            } else {
                Toast.makeText(this, "歌单中没有歌曲可播放", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupRecyclerView() {
        songAdapter = new SongAdapter(
                (song, position) -> {
                    List<Song> currentList = songAdapter.getCurrentList();
                    if (currentList != null && !currentList.isEmpty() && sharedViewModel != null) {
                        sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), position);
                    }
                },
                (song, anchorView) -> {
                    if (getSupportFragmentManager() != null && song != null) {
                        // 传入 playlistIdContext，以便 SongOptionsDialogFragment 知道要显示“从当前歌单移除”
                        SongOptionsDialogFragment.newInstanceForPlaylist(song.getId(), playlistId)
                                .show(getSupportFragmentManager(), SongOptionsDialogFragment.TAG);
                    }
                }
        );
        recyclerViewSongs.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewSongs.setAdapter(songAdapter);
    }

    private void observeViewModel() {
        playlistViewModel.getPlaylistDetails(playlistId).observe(this, playlist -> {
            currentPlaylistForMenu = playlist; // 保存当前歌单实体，用于编辑和删除
            if (playlist != null && getSupportActionBar() != null) {
                if (!playlist.getName().equals(getSupportActionBar().getTitle().toString())) {
                    getSupportActionBar().setTitle(playlist.getName());
                }
                // 歌单封面URI可以在这里用来设置Toolbar背景或CollapsingToolbarLayout (如果使用的话)
            }
            invalidateOptionsMenu(); // 歌单加载后更新菜单项（例如删除按钮的可用性）
        });

        playlistViewModel.getSongsForPlaylist(playlistId).observe(this, songs -> {
            if (songs != null && !songs.isEmpty()) {
                songAdapter.submitList(new ArrayList<>(songs)); // 传递副本
                tvEmptyPlaylist.setVisibility(View.GONE);
                recyclerViewSongs.setVisibility(View.VISIBLE);
                fabPlayAll.show();
            } else {
                songAdapter.submitList(new ArrayList<>());
                tvEmptyPlaylist.setText(getString(R.string.playlist_empty));
                tvEmptyPlaylist.setVisibility(View.VISIBLE);
                recyclerViewSongs.setVisibility(View.GONE);
                fabPlayAll.hide();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.playlist_songs_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem deleteItem = menu.findItem(R.id.action_playlist_songs_delete_playlist);
        MenuItem editItem = menu.findItem(R.id.action_playlist_songs_edit_info);
        // 只有加载到歌单实体后，编辑和删除才可用
        boolean enabled = currentPlaylistForMenu != null;
        if (deleteItem != null) deleteItem.setVisible(enabled);
        if (editItem != null) editItem.setVisible(enabled);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish(); // 修改为 finish()，因为这是Activity，不是Fragment
            return true;
        } else if (itemId == R.id.action_playlist_songs_edit_info) {
            if (currentPlaylistForMenu != null) {
                showEditPlaylistInfoDialog(currentPlaylistForMenu);
            }
            return true;
        } else if (itemId == R.id.action_playlist_songs_delete_playlist) {
            if (currentPlaylistForMenu != null) {
                showDeletePlaylistConfirmationDialog(currentPlaylistForMenu);
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 显示编辑歌单信息的对话框。
     * @param playlistToEdit 要编辑的歌单实体。
     */
    private void showEditPlaylistInfoDialog(@NonNull final Playlist playlistToEdit) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_create_edit_playlist, null); // 复用布局
        builder.setView(dialogView);

        final TextInputLayout tilPlaylistName = dialogView.findViewById(R.id.textInputLayout_playlist_name_dialog);
        final EditText etPlaylistName = dialogView.findViewById(R.id.editText_playlist_name_dialog);
        final TextInputLayout tilPlaylistDesc = dialogView.findViewById(R.id.textInputLayout_playlist_desc_dialog);
        final EditText etPlaylistDesc = dialogView.findViewById(R.id.editText_playlist_desc_dialog);

        builder.setTitle("编辑歌单信息");
        etPlaylistName.setText(playlistToEdit.getName());
        etPlaylistDesc.setText(playlistToEdit.getDescription() != null ? playlistToEdit.getDescription() : "");

        builder.setPositiveButton("保存", (dialog, which) -> {
            String newName = etPlaylistName.getText().toString().trim();
            String newDescription = etPlaylistDesc.getText().toString().trim();

            if (newName.isEmpty()) {
                tilPlaylistName.setError("歌单名称不能为空");
                Toast.makeText(this, "歌单名称不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            tilPlaylistName.setError(null);

            // 更新 Playlist 对象
            playlistToEdit.setName(newName);
            playlistToEdit.setDescription(newDescription);
            // 注意：其他字段如 songCount, creationDate, coverArtUri 不需要在这里修改，它们由其他逻辑管理
            playlistViewModel.updatePlaylist(playlistToEdit);
            Toast.makeText(this, "歌单信息已更新", Toast.LENGTH_SHORT).show();
            // Toolbar 标题会在 getPlaylistDetails LiveData 更新时自动刷新 (通过 observeViewModel)
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        builder.show();
    }

    private void showDeletePlaylistConfirmationDialog(@NonNull final Playlist playlistToDelete) {
        new AlertDialog.Builder(this)
                .setTitle("删除歌单")
                .setMessage("确定要删除歌单 “" + playlistToDelete.getName() + "” 吗？此操作不可撤销，歌单内的歌曲不会被删除。")
                .setPositiveButton(R.string.ok, (dialog, which) -> {
                    if (playlistViewModel != null) {
                        playlistViewModel.deletePlaylist(playlistToDelete);
                        Toast.makeText(this, "歌单 “" + playlistToDelete.getName() + "” 已删除", Toast.LENGTH_SHORT).show();
                        finish(); // 删除后关闭当前歌单详情页
                    }
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }
}
